<!-- 远程文件对话框 -->
<template>
  <a-modal v-model:visible="visible" :mask="false" width="900px" style="top: 30px;" @cancel="modalClose"
    :destroyOnClose="true">
    <template #title>
      <div ref="modalTitleRef" style="width: 100%">{{ "服务器设置" }}</div>
    </template>
    <template #modalRender="{ originVNode }">
      <div :style="transformStyle">
        <component :is="originVNode" />
      </div>
    </template>
    <a-spin :spinning="loading">
      <a-form :model="formState" name="formState" layout="inline" autocomplete="off">
        <a-row style="margin-bottom: 10px">
          <a-form-item label="服务器IP" name="serverIP">
            <a-input v-model:value="formState.serverIP"> </a-input>
          </a-form-item>
          <a-form-item label="端口" name="serverPort">
            <a-input v-model:value="formState.serverPort">
            </a-input>
          </a-form-item>
          <a-form-item label="传输方式" name="transmissionType">
            <a-radio-group v-model:value="formState.transmissionType" :options="plainOptions" />
          </a-form-item>
        </a-row>
        <a-form-item name="btn" style="width: 690px">
          <a-input v-model:value="formState.newPath" placeholder="当前路径" :readonly="true">
            <template #prefix>
              <FolderOutlined />
            </template>
          </a-input>
        </a-form-item>
        <a-form-item name="btn">
          <a-button type="default" @click="downback">返回上级</a-button>
        </a-form-item>
      </a-form>
      <!-- 路径选择 -->
      <div class="ftp-link-big">
        <div class="directory-list-left">
          <table>
            <thead style="position: sticky; top: 0;">
              <tr>
                <th width="200" align="left">磁盘</th>
              </tr>
            </thead>
            <tbody>
              <tr v-for="(item, index) in pathList" :key="index" @dblclick="getChildDir(item)">
                <td>
                  <FolderFilled style="color: #ffb515" /> {{ item }}
                </td>

              </tr>
            </tbody>
          </table>
        </div>
        <div class="ftp-link-directory-list">
          <table class="directory-list">
            <thead style="position: sticky; top: 0;">
              <tr>
                <th width="800" align="left">
                  <div style="position: relative" @click="clName" @mouseover="mouseName = true"
                    @mouseleave="mouseName = false">
                    <span>名称</span>
                    <div class="iconSty" v-show="mouseName">
                      <DownOutlined v-if="!clNameIsshow" />
                      <UpOutlined v-else></UpOutlined>
                    </div>
                    <!-- <div>
                      <DownOutlined
                        style="font-size: 10px; position: absolute; right: 0; top: 50%; transform: translateY(-50%);" />
                    </div> -->
                  </div>
                </th>
                <th width="200" align="left">
                  <a-dropdown v-model:visible="dropIsshow" :trigger="['click']">

                    <div style="display: flex; justify-content: space-between;" @mouseover="mouseType = true"
                      @mouseleave="mouseType = false">
                      <span>类型</span>
                      <div v-show="mouseType">
                        <DownOutlined v-if="!dropIsshow" style="font-size: 10px;; transform: translateY(-1px)" />
                        <UpOutlined v-else style="font-size: 10px; transform: translateY(-1px)" />
                      </div>
                    </div>

                    <template #overlay>

                      <a-card style="padding: 10px; width: 110px;">
                        <a-checkbox-group v-model:value="fileType" name="checkboxgroup" :options="fileTypeList"
                          @change="changeFileType" />
                      </a-card>
                    </template>
                  </a-dropdown>
                </th>
                <th width="200" align="left">
                  <div style="position: relative" @click="clSize" @mouseover="mouseSize = true"
                    @mouseleave="mouseSize = false">
                    <span>大小</span>
                    <div class="iconSty" v-show="mouseSize">
                      <DownOutlined v-if="!clSizeIsshow" />
                      <UpOutlined v-else></UpOutlined>
                    </div>
                  </div>
                </th>
              </tr>
            </thead>
            <tbody v-if="pathArr && pathArr.length > 0">
              <tr :class="{ active: fileName.includes(item.name) }" v-for="(item, index) in pathArr" :key="index"
                @dblclick="getChildDir(item.name, item.type)" @click="pitchOn(item.name, item.type)">
                <td>
                  <FolderFilled class="yellow-folder" v-if="item.type === 'd'" />
                  <FileTwoTone v-else /> {{ item.name }}
                </td>
                <td>{{ null }}</td>
                <td>{{ item.size }}</td>
              </tr>
            </tbody>
            <div v-else>
              <a-empty :image="simpleImage" />
            </div>
          </table>
        </div>
      </div>
      <a-divider style="background-color: #d9d9d9; margin-bottom: 0" />


    </a-spin>
    <template #footer>
      <div style="display: flex; justify-content: space-between">
        <div style="display: flex; align-items: center;">
          <div style="margin-right: 10px;">文件名:</div>
          <a-select v-model:value="fileName" mode="multiple" style="width: 300px" :open="false"></a-select>
        </div>
        <div>
          <a-button key="back" @click="modalClose">取消</a-button>
          <a-button key="submit" type="primary" @click="setPublishParams">打开</a-button>
        </div>
      </div>
    </template>
  </a-modal>
</template>

<script>
import {
  // RollbackOutlined,
  FolderOutlined,
  FolderFilled,
  FileTwoTone,
  DownOutlined,
  UpOutlined
} from "@ant-design/icons-vue";
import { getFTP, getFTPList } from '@/api/dataDownloadPublish'
import { message } from "ant-design-vue";
import { Empty } from 'ant-design-vue'
import { Draggable } from "@/mixins/DraggableMixin.js"
export default {
  mixins: [Draggable],
  name: "DialogSetFtp",
  components: {
    // RollbackOutlined,
    FolderOutlined,
    FolderFilled,
    FileTwoTone,
    DownOutlined,
    UpOutlined,
  },
  data() {
    return {
      mouseName: false,
      mouseType: false,
      mouseSize: false,
      simpleImage: Empty.PRESENTED_IMAGE_SIMPLE,
      clNameIsshow: false, // 名称图标的切换
      dropIsshow: false, // 类型图标的切换
      clSizeIsshow: false, // 大小图标的切换
      visible: true,
      pathList: [],
      fileType: [], //类型
      fileTypeList: [], //类型的下拉列表
      newPath: '',
      formState: {
        serverIP: "",
        serverPort: "",
        transmissionType: 1,
        // path: "e:\\",
        // newPath: 'e:\\',
        path: "",
        newPath: "",
      },
      pathArr: [], //渲染页面
      newPathArr: [], //做数据存储
      loading: false,
      fileName: [], //文件名称
      flag: false,
      plainOptions: [ //传输方式
        { label: 'FTP', value: 1 },
        { label: 'SFTP', value: 2 },
        { label: 'HTTP', value: 3 },
      ]
    };
  },
  props: {
    list: {
      type: String
    },
  },
  created() {
    this.getFTPListLeft()
  },
  methods: {
    // 根据大小排序逻辑
    compareSize() {
      this.pathArr.sort((a, b) => {
        if (a.type === 'd' && b.type === 'r') {
          return this.clSizeIsshow ? 1 : -1; // -1:文件夹在前，1:文件在前
        } else if (a.type === 'r' && b.type === 'd') {
          return this.clSizeIsshow ? -1 : 1; // -1:文件夹在前，1:文件在前
        } else if (a.type === 'r' && b.type === 'r') {
          return this.clSizeIsshow ? b.size - a.size : a.size - b.size; // 文件按照size进行排序
        } else {
          return 0; // 保持原有顺序
        }
      })
    },
    // 点击大小排序
    clSize() {
      this.clSizeIsshow = !this.clSizeIsshow //icon切换
      this.clNameIsshow = false
      if (this.pathArr.length === 0) return
      this.compareSize()
    },
    // 根据name的值来排序
    compareName(a, b) {
      let nameA = a.name;
      let nameB = b.name;

      // 判断是否为数字
      let isNumber = function (str) {
        return /^\d+$/.test(str);
      };

      // 判断是否为字母
      let isLetter = function (str) {
        return /^[a-zA-Z]+$/.test(str);
      };

      // 判断是否为汉字
      let isChinese = function (str) {
        return /^[\u4E00-\u9FA5]+$/.test(str);
      };

      // 判断是否为特殊字符
      let isSpecialCharacter = function (str) {
        return !isNumber(str) && !isLetter(str) && !isChinese(str);
      };

      if (!this.clNameIsshow) {
        // 定义优先级
        let priority = {
          number: 0,
          letter: 1,
          chinese: 2,
          specialCharacter: 3
        };
        // 获取优先级
        let getPriority = function (str) {
          if (isNumber(str)) {
            return priority.number;
          }
          if (isLetter(str)) {
            return priority.letter;
          }
          if (isChinese(str)) {
            return priority.chinese;
          }
          return priority.specialCharacter;
        };
        // 比较优先级
        let priorityA = getPriority(nameA.charAt(0));
        let priorityB = getPriority(nameB.charAt(0));

        if (priorityA < priorityB) {
          return -1;
        }
        if (priorityA > priorityB) {
          return 1;
        }
        // 如果优先级相同，则按照字符串本身的比较结果排序
        return nameA.localeCompare(nameB);
      } else {
        // 定义优先级
        let priority = {
          specialCharacter: 0,
          chinese: 1,
          letter: 2,
          number: 3
        };

        // 获取优先级
        let getPriority = function (str) {
          if (isSpecialCharacter(str)) {
            return priority.specialCharacter;
          }
          if (isChinese(str)) {
            return priority.chinese;
          }
          if (isLetter(str)) {
            return priority.letter;
          }
          return priority.number;
        };

        // 比较优先级
        let priorityA = getPriority(nameA.charAt(0));
        let priorityB = getPriority(nameB.charAt(0));

        if (priorityA < priorityB) {
          return -1; // 倒序排序
        }
        if (priorityA > priorityB) {
          return 1; // 倒序排序
        }
      }
      return nameB.localeCompare(nameA);
    },
    // 根据类型排序
    compareTypeAndName(a, b) {
      let typeA = a.type;
      let typeB = b.type;

      // 比较类型
      if (typeA === 'd' && typeB === 'r') {
        return this.clNameIsshow ? 1 : -1; // -1 文件夹排在前面
      }
      if (typeA === 'r' && typeB === 'd') {
        return this.clNameIsshow ? -1 : 1; // 文件排在后面
      }

      // 类型相同，按照名称排序
      return this.compareName(a, b);
    },
    // 点击名称排序
    clName() {
      this.clNameIsshow = !this.clNameIsshow //icon切换
      this.clSizeIsshow = false
      if (this.pathArr.length === 0) return
      this.pathArr = this.pathArr.sort(this.compareTypeAndName)
    },
    // 选中类型
    changeFileType(e) {
      this.pathArr = []
      this.clNameIsshow = false
      this.clSizeIsshow = false
      if (e.length !== 0) {
        this.newPathArr.forEach(item => {
          e.forEach(ev => {
            if (item.type === ev) {
              this.pathArr.push(item)
            }
          })
        })
      } else {
        this.pathArr = this.newPathArr
      }
    },
    async getFTPListLeft() {
      try {
        this.loading = true
        const resList = await getFTPList()
        this.pathList = resList.content
      } catch (error) {
        console.log(error);
      } finally {
        this.loading = false
      }
    },
    // 返回上级
    downback() {
      this.newPath = ''
      if (this.formState.path !== this.pathList.join('||')) {
        let parentPath = this.formState.path.substring(0, this.formState.path.lastIndexOf("\\", this.formState.path.length - 2) + 1);
        this.formState.path = parentPath
        this.formState.newPath = parentPath
      } else {
        // this.formState.path = "e:\\"
        // this.formState.newPath = "e:\\"
      }
      if (!this.formState.newPath) {
        this.pathArr = [] // 数据清空1
        this.newPathArr = [] // 数据清空2
        this.fileTypeList = [] //类型清空
        this.fileName = [] //选择的文件名清空
        this.clNameIsshow = false //名称的Icon还原
        return
      }
      this.getFTPlist()
    },
    pitchOn(info) {
      // if (!this.flag) {
      //   this.fileName = []
      // }
      this.fileName = []
      this.flag = true
      setTimeout(() => {
        if (this.flag) {

          if (this.list === 'directory') {
            const haveFile = this.fileName.find(item => {
              if (item == info) {
                return item
              }
            })
            if (haveFile) {
              return message.warning('您已选择了该目录~')
            }
            this.fileName.push(info)
          } else {
            const haveFile = this.fileName.find(item => {
              if (item == info) {
                return item
              }
            })
            if (haveFile) {
              return message.warning('您已选择了该文件~')
            }
            this.fileName.push(info)
          }
        }
      }, 0)

    },
    async getChildDir(info, type) {
      if (this.formState.path.includes(info)) {
        return
      } else {
        if (type == 'd') {
          if (this.newPath) {
            let parentPath = this.formState.newPath.substring(0, this.formState.newPath.lastIndexOf("\\", this.formState.newPath.length - 2) + 1);
            this.formState.path = parentPath; // 更新新路径为当前选中的文件/文件夹
            this.formState.newPath = parentPath; // 更新新路径为当前选中的文件/文件夹
            this.newPath = ''
          } else {
            // this.formState.path += (info + "\\")
            // this.formState.newPath += (info + "\\")
          }



          this.getFTPlist(info)

        } else if (!type) {
          this.formState.path = ""
          this.formState.newPath = ""
          this.newPath = ""
          this.getFTPlist(info)
        } else {
          this.newPath = this.formState.newPath.substring(0, this.formState.newPath.lastIndexOf("\\") + 1);
          this.formState.newPath = this.newPath; // 更新新路径为当前选中的文件/文件夹
          this.formState.path = this.newPath; // 更新当前路径为当前选中的文件/文件夹


        }

      }
    },
    // 请求数据
    async getFTPlist(info) {
      this.loading = true
      try {
        if (info && this.pathList.includes(info)) {
          this.formState.newPath = info
          this.formState.path = info
        } else if (info) {
          this.formState.newPath += (info + "\\")
          this.formState.path += (info + "\\")
        }
        const res = await getFTP(this.formState.path)
        this.flag = false
        if (this.list === 'directory') {
          const content = res.content.filter(item => item.type == 'd')
          this.pathArr = content || []
          this.newPathArr = content || []
        } else {
          this.pathArr = res.content ?? []
          this.newPathArr = res.content ?? []
        }

        this.fileTypeList = this.pathArr.map(item => {
          return { label: item.type === 'd' ? '文件夹' : '文件', value: item.type }
        })
        this.fileTypeList = Array.from(new Set(this.fileTypeList.map(JSON.stringify)), JSON.parse)
        this.fileType = [] //每一次跳转之后，清空类型
        this.clNameIsshow = false //每次跳转之后，名称排序图标重置
        this.fileName = []
        if (info && !this.pathList.includes(info)) {
          this.fileName.push(info)
        }
        // 每次跳转之后，滚动条回到顶部
        const tableElement = document.querySelector('.ftp-link-directory-list');
        tableElement.scrollTop = 0;

        this.loading = false
      } catch (error) {
        if (error.data === null) {
          let parentPath = this.formState.path.substring(0, this.formState.path.lastIndexOf("\\", this.formState.path.length - 2) + 1)
          this.formState.path = parentPath
          this.formState.newPath = parentPath
        }
        this.loading = false
      }
    },
    // 配置返回的分发参数
    async setPublishParams() {
      if (this.fileName.length === 0) return message.warning('请选择文件')
      if (this.list === 'directory') {
        try {
          this.loading = true
          // ************************************
          // request
          this.$emit('submitY', this.formState, this.fileName)
          this.modalClose()
          message.success('服务器设置成功')
        } catch (error) {
          console.log(error);
        } finally {
          this.loading = false
        }
      }
      else {
        this.fileName.forEach(item => {
          this.$emit('submitY', this.formState.newPath + item)
        })
        this.modalClose()
      }
    },
    // 关闭弹窗
    modalClose() {
      this.$emit("close");
    },
  },
};
</script>

<style lang="scss" scoped>
.ftp-link-big {
  display: flex;
  justify-content: space-between;
}

.directory-list-left {
  margin-right: 2px;
  margin-top: 10px;
  height: 280px;
  overflow-y: auto;

  thead {
    th {
      background: #ebebeb;
      height: 30px;
      padding: 5px;
      margin-right: 1px;
      border-right: 1px solid #ccc;
    }

    th:last-child {
      border-right: none;
    }
  }

  tbody {
    tr {
      cursor: pointer;
      height: 40px;

      td {
        padding: 5px 10px;

        .yellow-folder {
          color: #ffb515;
        }
      }
    }

    tr:hover {
      td {
        background: #b7d7f9;
      }
    }
  }
}

.ftp-link-directory-list {
  box-sizing: border-box;
  margin-top: 10px;
  height: 280px;
  overflow-y: auto;
}

.directory-list {
  thead {
    th {
      background: #ebebeb;
      height: 30px;
      padding: 5px;
      margin-right: 1px;
      border-right: 1px solid #ccc;
    }

    th:last-child {
      border-right: none;
    }
  }

  tbody {
    tr {
      cursor: pointer;
      height: 40px;

      td {
        padding: 5px 10px;

        .yellow-folder {
          color: #ffb515;
        }
      }
    }

    tr:hover {
      td {
        background: #b7d7f9;
      }
    }
  }
}

.iconSty {
  font-size: 10px;
  position: absolute;
  top: -10px;
  left: 50%;
  transform: translateX(-50%);
}

.active {
  background-color: #b7d7f9;
  border: 1px solid #efefef;
}
</style>